package com.xcc.core.netty.client;


import java.math.BigInteger;

import com.xcc.core.netty.NettyLengthClient;
import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.netty.model.LengthModel;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ClientLengthHandler extends SimpleChannelInboundHandler<LengthModel> {


    public ClientLengthHandler() {
        //    startProClient();
    }



    @Override
    public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
        /*
         * Integer.parseInt("0x"+ctx.channel().id() .asShortText(), 16);
         */
        int id=  new BigInteger(ctx.channel().id()
            .asShortText(), 16).intValue();
        System.out.println("连接服务器客户端"+ id);
        ManagerChannel.getAllServer().put("3389",ctx.channel()); 


        /*
         * LengthModel msg=new LengthModel(); byte[] bs="connect".getBytes(); msg.setBs(bs);
         * msg.setLength(bs.length); msg.setId(id); ctx.writeAndFlush(msg);
         */
    }
    //传给客户端id 这里会拿到client2 id
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LengthModel msg)
        throws Exception {
              System.out.println(new String(msg.getBs()));
        if("connect".equals(new String(msg.getBs()))) {
            System.out.println("代理客户端："+msg.getId());
            NettyLengthClient.startProClient(msg.getId());
        }else {
            int id=  new BigInteger(ctx.channel().id()
                .asShortText(), 16).intValue();
            System.out.println("msg:"+msg.getId());
            Channel ch=ManagerChannel.getServerChannel2(msg.getId()+"");
            System.out.print("接收数据："); 
            for(byte b:msg.getBs()) {
                System.out.print((0xff&b)+" ");
            }
            String length=new String(msg.getBs());
            System.out.print("接收数据长度"+msg.getLength()+"or"+msg.getBs().length); 
            System.out.println();
            ByteBuf buf=Unpooled.copiedBuffer(msg.getBs());
            ch.writeAndFlush(buf);    
        }
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
        super.exceptionCaught(ctx, cause);
    }

}
